package micro.data.datasource;

import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by hldev on 17-11-20.
 * 系统库配置
 * @author hldev
 */
@Configuration
@Data
@ConfigurationProperties(prefix = "spring.datasource")
@MapperScan(basePackages = {"micro.data.mapper"}, sqlSessionFactoryRef = "systemRepoSqlSessionFactory")
public class SystemRepoConfig {

    private String jdbcUrl;

    private String username;

    private String driverClassName;

    private String password;

    private Integer maximumPoolSize;

    private Integer minimumIdle;

    private String model="micro.user.data.model";
    private String classPath="classpath:/mybatis/*.xml";

    @Primary
    @Bean(name = "systemRepoDatasource")
    public DataSource dataSource() {
       return new HikariConfig(jdbcUrl,username,driverClassName,password,maximumPoolSize,minimumIdle).buildHikari();
    }

    @Primary
    @Bean(name = "systemRepoTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("systemRepoDatasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "systemRepoSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("systemRepoDatasource") DataSource dataSource) throws Exception {
        return new SesseionFactoryBean(model,classPath).newInstance(dataSource);
    }
    @Bean("jdbcTemplateSystem")
    @Primary
    public JdbcTemplate jdbcTemplate(@Qualifier("systemRepoDatasource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
